﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using HtmlAgilityPack;

namespace TaxiDispatchClient
{
    public partial class AdMachineAdListForm : DevExpress.XtraEditors.XtraForm
    {
        
       
        //设置单个站点的广告
        public AdMachineAdListForm(string imgUrl)
        {
            InitializeComponent();
            string[] arry = imgUrl.Split('|');
            if (arry.Length>0)
            {
                _imgUrlList = new List<string>();
                foreach (string url in arry)
                {
                    if (url.Trim()!="")
                    {
                        _imgUrlList.Add(url);
                    }
                }
            }
            StrImgUrl = imgUrl;           
        }

        //设置多个站点的广告
        public AdMachineAdListForm( List<string> stationlist)
        {
            InitializeComponent();
            _stationList = stationlist;
        }

        private void AdMachineAdListForm_Load(object sender, EventArgs e)
        {
            DevExpress.Data.CurrencyDataController.DisableThreadingProblemsDetection = true;
            _dtAdList = new DataTable();
            _dtAdList.Columns.Add("ImgName");
            _dtAdList.Columns.Add("Size");
            _dtAdList.Columns.Add("UpdateTime");
            _dtAdList.Columns.Add("IsUsed", typeof(bool));

            btn_load.Enabled = false;
            Thread threadLoadImg = new Thread(LoadUrlImg);
            threadLoadImg.IsBackground = true;
            threadLoadImg.Start();
        }

        public string StrImgUrl;
        private DataTable _dtAdList;
        private List<string> _imgUrlList;
        private List<string> _stationList; 

        private void btn_load_Click(object sender, EventArgs e)
        {           
            if (textBox_url.Text.Trim()=="")
            {
                XtraMessageBox.Show("请输入广告图片存在的网络地址");
                textBox_url.Focus();
                return;
            }
            btn_load.Enabled = false;
            Thread threadLoadImg = new Thread(LoadUrlImg);
            threadLoadImg.IsBackground = true;
            threadLoadImg.Start();
        }

        private void LoadUrlImg()
        {
            _dtAdList.Rows.Clear();

            string _url = textBox_url.Text ;
            CookieContainer container = new CookieContainer();
            string result = SendDataByGet(_url, "", ref container);
            if (result=="")
            {
                XtraMessageBox.Show("无效的网络地址，请核实！");
                return;
            }
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(result);
            HtmlNode rootNode = document.DocumentNode;
            HtmlNode mainnode = HtmlNode.CreateNode(rootNode.OuterHtml);
            //HtmlNodeCollection nodecoln =
            //mainnode.SelectNodes("//html[1]/body[1]/pre[1]/a");
            mainnode =
            mainnode.SelectSingleNode("//html[1]/body[1]/pre[1]");
           
            for (int i = 0; i < mainnode.ChildNodes.Count; i++)
            {
                HtmlNode temp = mainnode.ChildNodes[i];
                if (temp.Name.Contains("text"))
                {
                    DataRow row = _dtAdList.NewRow();
                    string info = temp.InnerHtml;
                    //" 2012/12/7    16:21          317 "
                    string[] arr = info.Split(' ');
                    List<string> arList = new List<string>();
                    foreach (string s in arr)
                    {
                        if (s.Trim() != "")
                        {
                            arList.Add(s);
                        }
                    }
                    if (arList.Count == 3)
                    {
                       row["UpdateTime"] = arList[0] + " " + arList[1];
                       row["Size"] = arList[2];
                    }
                    temp = mainnode.ChildNodes[i + 1];
                    string name  = temp.InnerHtml;
                    row["ImgName"] = name;
                    string url = temp.Attributes["href"].Value;                  
                    row["IsUsed"] = "False";
                    if (_imgUrlList!=null &&
                        _imgUrlList.Contains(name))
                    {
                        row["IsUsed"] = "True";    
                    }
                    _dtAdList.Rows.Add(row);
                }
            }
            BeginInvoke(new MethodInvoker(() =>
                {
                    gridControl1.DataSource = _dtAdList;
                    btn_load.Enabled = true;
                }));
        }
        
        //Get方法 返回数据        
        private string SendDataByGet(string Url, string postDataStr, ref CookieContainer cookie)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            if (cookie.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookie = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookie;
            }
            string retString = "";
            try
            {
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = "www";
                //  "https://passport.csdn.net/account/loginbox?callback=logined&hidethird=1&from=http%3a%2f%2fbbs.csdn.net%2f";
                //request.Headers
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch (Exception ex)
            {
                retString = "";
            }
           
            return retString;
        }        
    
        private void btn_ok_Click(object sender, EventArgs e)
        {
            string value ;
            string url = "";
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["IsUsed"].ToString();
                if (value == "True")
                {
                    string href = gridView1.GetRowCellValue(i, "ImgName").ToString();
                    url +=  href + "|";
                }
            }
            //设置单个站点的广告
            if (_stationList==null)
            {
                StrImgUrl = url;
                Close();
            }
            else
            {
                //设置多个站点的广告
                string list = "";
                foreach (string station in _stationList)
                {
                    list += "'" + station + "'" + ",";
                }
                if (list.Contains(","))
                {
                    list = list.Remove(list.Length - 1);
                }
                int succeed = MainForm.PositionService.AdMachineUpdateUrlInList(url, list);
                string strShow = "成功更新" + succeed + "个站点,失败"
                     + (_stationList.Count - succeed).ToString() + "个";
                XtraMessageBox.Show(strShow);
            }
          
        }


        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PhoneUserForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion
    }
}